<template>
	<div class="prizeBox">
		<div class="ladderBox">
			<el-tabs 
				v-model="editableTabsValue" 
				type="card" 
				:closable="repeatRecord == 0" 
				@tab-remove="removeLadder"
				:before-leave="changeTab"
				style="width:98%"
				>
				<el-tab-pane v-for="(item,index) in editableTabs" :key="item.name" :label="item.title" :name="item.name" >
					<AddCashback  :id="'ladder'+(index+1)" :prizeID="prizeID" :awardSort="index+1" :ref="'prizeItem'+(index+1)" :lotterData="lotterData"></AddCashback>
				</el-tab-pane>
			</el-tabs>
			<div class="addLadderBtn el-tabs__item is-top" @click="addLadderBtn"><span class="addIcon">+</span>添加阶梯</div>
		</div>
		<div class="ladderBtns">
			<div class="pageBtn btn next" @click="goDone(-1,$event)">上一步</div>
			<div class="pageBtn btn save" @click="goDone(0,$event)">保存</div>
			<div class="pageBtn btn next" @click="goDone(1,$event)">下一步</div>
		</div>
	</div>
</template>

<script>
let position = {
  "1": "一",
  "2": "二",
  "3": "三",
  "4": "四",
  "5": "五",
  "6": "六",
  "7": "七",
  "8": "八",
  "9": "九",
  "10": "十",
  "11": "十一",
  "12": "十二"
};
import Step from "_components/Step";
import AddCashback from "./children/AddCashback";
import {
  SAVE_LOTTERY,
  EDIT_LOTTERY,
  DEL_LOTTERY,
  FIND_LOTTERY_BY_CODE,
  FIND_CASHBACK_BY_CODE,
  ADD_OR_UPDATE_CASHBACK
} from "@/config/url";
import Bus from "@/bus.js";
import { publicVM } from "_config/public.js";

export default {
  components: {
    Step,
    AddCashback
  },
  mixins: [publicVM],
  created() {
    this.initData();
    let that = this;
    Bus.$off("refreshList");
    Bus.$on("refreshList", val => {
      that.$store.commit("setFirstCouponData", null);
      that.$store.commit("setSecCouponData", null);
      this.repeatRecordContent = null;
      that.getFirstLottery();
    });
    Bus.$off('refreshCoupon')
    Bus.$on("refreshCoupon", val => {
      if (this.repeatRecord == 0) {
        that.getFirstCounpon(val, 1);
      } else {
        that.getSecCounpon(val);
      }
    });
    sessionStorage.setItem("lotterySort", 1);
    this.getFirstLottery();////
  },
  updated() {
    let that = this;
    if (this.isAdd) {
      that.$nextTick(() => {
        that.getAddBtnPos();
      });
      this.isAdd = false;
    }
    if (this.repeatRecord == 1) {
      $(".addLadderBtn").hide();
    } else {
      $(".addLadderBtn").show();
    }
  },
  data() {
    return {
      editableTabsValue: "ladder1",
      editableTabs: [],
      tabIndex: 1,
      isAdd: true,
      tabNameIndex: 1, //保存已经设置的内容，
      activityCode: sessionStorage.getItem("activityCode"),
      repeatRecord: sessionStorage.getItem("repeatRecord"),
      prizeID: null, //阶梯ID
      repeatRecordContent: null, //保存的数据
      isRemove: false, //正在删除
      isAddimg: false, //正在添加阶梯
      showStation: false, //显示电站
      type: {
        //电站选择
        type: 1
      },
      lotterData: null, //阶梯结果
      isIdentical: null, //0 一致，1 不一致
      count: 0 //复录奖励个数
    };
  },
  watch: {
    tabIndex(n, o) {
      if (n > 1 && n > o) {
        this.isAdd = true;
      } else {
        this.isAdd = false;
      }
    }
  },
  computed: {
    lotteryNums() {
      return this.editableTabs.length;
    }
  },
  methods: {
    getAddBtnPos() {
      let w = $(".prizeBox .el-tabs__nav").width();
      $(".addLadderBtn").css("left", w);
    },
    addLadderBtn() {
      let that = this;
      that.isAdd = false;
      let isAdd = that.addLadder();
      that.initData();
      if (isAdd == "1") {
        that.getCode(that.editableTabs.length);
      }
    },
    initData() {
      if (this.$store.getters.getFirstLotteryData) {
        this.$store.commit("setFirstLotteryData", null);
      }
      if (this.$store.getters.getSecLotteryData) {
        this.$store.commit("setSecLotteryData", null);
      }
      if (this.$store.getters.getFirstCouponData) {
        this.$store.commit("setFirstCouponData", null);
      }
      if (this.$store.getters.getSecCounponData) {
        this.$store.commit("setSecCouponData", null);
      }
    },
    getFirstLottery(id) {
      let that = this;
      this.$fetch(FIND_LOTTERY_BY_CODE, {
        activityCode: this.activityCode,
        repeatRecord: "0"
      })
        .then(res => {
          if (res.status == 1) {
            this.initData();
            if (res.data.length < 1) {
              // this.addLadder()
              this.getCode(1);
              this.$store.commit("setFirstLotteryData", null);
            } else {
              let data = res.data;
              that.lotterData = res.data;
              this.editableTabs = [];
              this.$store.commit("setFirstLotteryData", res.data);
              that.repeatRecordContent =
                res.data[sessionStorage.getItem("lotterySort") - 1];
              this.$store.commit(
                "setCurrentLottery",
                res.data[sessionStorage.getItem("lotterySort") - 1].id
              );
              that.prizeID = id || res.data[0].id;
              for (let i = 0; i < res.data.length; i++) {
                that.editableTabs.push({
                  title: "阶梯" + (i + 1),
                  name: "ladder" + (i + 1),
                  content: "New Tab content"
                });
                that.tabIndex++;
                if (res.data[i].isIdentical == "1" && this.repeatRecord == 1) {
                  $("#tab-ladder" + (i + 1)).css("color", "red");
                }
              }
              this.getFirstCounpon(
                this.$store.getters.getFirstLotteryData[
                  sessionStorage.getItem("lotterySort") - 1
                ].id
              );
            }
          }
        })
        .catch(err => {
          console.log(err);
          this.$message({
            message: "获取失败",
            type: "warning"
          });
        });
    },
    getSecLottery() {
      let that = this;
      let id = null;
      this.$fetch(FIND_LOTTERY_BY_CODE, {
        activityCode: this.activityCode,
        repeatRecord: "1"
      })
        .then(res => {
          if (res.status == 1) {
            if (res.data.length > 0) {
              this.lotterData = res.data;
              this.$store.commit("setSecLotteryData", res.data);
              this.getSecCounpon(
                res.data[sessionStorage.getItem("lotterySort") - 1].id
              );
              this.$store.commit(
                "setCurrentLottery",
                res.data[sessionStorage.getItem("lotterySort") - 1].id
              );
              // that.prizeID = id||res.data[sessionStorage.getItem('lotterySort')-1].id
            } else {
              for (let i = 0; i < this.lotterData.length; i++) {
                this.getCode(i + 1);
              }
              // this.$store.commit('setSecCouponData','')
            }
          }
        })
        .catch(err => {
          console.log(err);
          this.$message({
            message: "获取失败",
            type: "warning"
          });
        });
    },
    getFirstCounpon(id, type) {
      let that = this;
      this.$fetch(FIND_CASHBACK_BY_CODE, {
        activityCode: this.activityCode,
        repeatRecord: "0",
        lotteryId: id
      })
        .then(res => {
          if (res.status == 1) {
            if (res.data.length > 0) {
              this.$store.commit("setFirstCouponData", null);
              this.$store.commit("setFirstCouponData", res.data);
              if (that.repeatRecord == 1) {
                that.getSecLottery();
              }
              if (type) {
                let pos = this.editableTabsValue.slice(-1);
                let itemRef = "prizeItem" + pos;
                this.$refs[itemRef][0].addItems();
              }
            } else {
              this.$store.commit("setFirstCouponData", []);
              let pos = this.editableTabsValue.slice(-1);
              let itemRef = "prizeItem" + pos;
              // that.$refs[itemRef][0].addRow();
              this.$refs[itemRef][0].addItems();
            }
          }
        })
        .catch(err => {
          console.log(err);
          this.$message({
            message: "获取失败",
            type: "warning"
          });
        });
    },
    getSecCounpon(id) {
      let that = this;
      id = this.$store.getters.getSecLotteryData[
        sessionStorage.getItem("lotterySort") - 1
      ].id;
      this.$fetch(FIND_CASHBACK_BY_CODE, {
        activityCode: this.activityCode,
        repeatRecord: "1",
        lotteryId: id
      })
        .then(res => {
          if (res.status == 1) {
            if (res.data.length > 0) {
              // this.$store.commit('setSecCouponData',null)
              this.$store.commit("setSecCouponData", res.data);
            } else {
              that.getPrizeID();
            }
          }
        })
        .catch(err => {
          console.log(err);
          this.$message({
            message: "获取失败",
            type: "warning"
          });
        });
    },
    getPrizeID() {
      let firstData = this.$store.getters.getFirstCouponData;
      if (
        this.$store.getters.getSecLotteryData &&
        !this.$store.getters.getSecCouponData
      ) {
        let id = this.$store.getters.getSecLotteryData[
          sessionStorage.getItem("lotterySort") - 1
        ].id;
        let param = [];
        for (let i = 0; i < firstData.length; i++) {
          let item = {};
          item.activityCode = this.activityCode;
          item.lotteryId = id;
          item.winningProbability = null;
          item.cashbackMoney = null;
          item.differentiate = null;
          item.cashbackSort = i + 1;
          item.repeatRecord = this.repeatRecord;
          param.push(item);
        }
        this.$post(ADD_OR_UPDATE_CASHBACK, {
          activityCashbacks: param
        })
          .then(res => {
            if (res.status == 1) {
              this.getSecLottery();
            } else {
              this.$message({
                message: res.data,
                type: "warning"
              });
            }
          })
          .catch(err => {
            console.log(err);
            this.$message({
              message: "操作失败",
              type: "warning"
            });
          });
      }
    },
    goDone(type, e) {
      if (type == -1) {
        this.$router.push("/settingIndex/newRuleCashback");
        Bus.$emit("changeStep");
      } else {
        let pos = this.editableTabsValue.slice(-1);
        let itemRef = "prizeItem" + pos;
        let a = this.$refs[itemRef][0].savePrize(0);
        // this.$refs[itemRef][0].saveLottery(0)
        if (type == 1) {
          Bus.$emit("changeStep");
          this.$router.push("/settingIndex/activityDone");
        }
      }
    },
    changeTab(n, o) {
      let pos = o.slice(-1);
      let newPos = n.slice(-1);
      let itemRef = "prizeItem" + pos;
      let tabNew = "prizeItem" + newPos;
      if (this.$refs[itemRef][0].checkPrize()) {
        sessionStorage.setItem("lotterySort", newPos);
        this.$store.commit("setPreLotterySort", pos);
        this.$store.commit(
          "setPreLottery",
          this.$store.getters.getCurrentLottery
        );

        if (this.isAdding) {
          this.$refs[itemRef][0].saveItem(newPos);
          this.editableTabsValue = "ladder" + newPos;
        }

        if (this.$refs[tabNew] && this.$refs[tabNew].length > 0) {
          if (this.$store.getters.getSecLotteryData) {
            this.$store.commit(
              "setCurrentLottery",
              this.$store.getters.getSecLotteryData[newPos - 1].id
            );
          } else {
            this.$store.commit(
              "setCurrentLottery",
              this.$store.getters.getFirstLotteryData[newPos - 1].id
            );
          }
          this.getFirstLottery();/////////////
        }

        if (!this.isRemove) {
          // this.$refs[itemRef][0].saveLottery(1); //保存切换前的阶梯奖项
          // this.$refs[itemRef][0].savePrize(1); //保存切换前的阶梯奖项/////////////////
        }

        this.isRemove = false;
        this.isAdding = false;
      } else if (this.$refs[itemRef][0].checkPrize() == undefined) {
        sessionStorage.setItem("lotterySort", newPos);
        this.$store.commit("setPreLotterySort", pos);
        this.$store.commit(
          "setPreLottery",
          this.$store.getters.getCurrentLottery
        );

        if (this.$refs[tabNew] && this.$refs[tabNew].length > 0) {
          if (this.$store.getters.getSecLotteryData) {
            this.$store.commit(
              "setCurrentLottery",
              this.$store.getters.getSecLotteryData[newPos - 1].id
            );
          } else {
            this.$store.commit(
              "setCurrentLottery",
              this.$store.getters.getFirstLotteryData[newPos - 1].id
            );
          }
          this.getFirstLottery();/////////
        }

        this.isRemove = false;
        this.isAdding = false;
      } else {
        this.$message({
          message: "请先完成当前阶梯设置",
          type: "warning"
        });
        return false;
      }
    },
    getCode(num) {
      //获取阶梯对应的编号
      let that = this;
      let param = {
        activityCode: this.activityCode,
        repeatRecord: this.repeatRecord,
        awardSort: num
      };
      param.awardObtain = 0;
      param.isIdentical = 0;
      this.$post(SAVE_LOTTERY, param)
        .then(res => {
          if (res.status == 1) {
            that.count++;
            that.prizeID = res.data;
            if (that.repeatRecord == 0) {
              that.getFirstLottery();
            } else {
              if (that.$store.getters.getFirstCouponData.length == that.count) {
                that.getSecLottery();
                that.count = 0;
              }
            }
          } else {
            this.$message({
              message: res.data,
              type: "warning"
            });
          }
        })
        .catch(err => {
          console.log(err);
          this.$message({
            message: "获取code失败",
            type: "warning"
          });
        });
    },
    addLadder() {
      let itemRef = "prizeItem" + sessionStorage.getItem("lotterySort");
      if (this.$refs[itemRef][0].checkPrize()) {
        //奖项不为空
        let tabNum = $(".ladderBox .el-tabs__item").length;
        if (tabNum == 10) {
          this.$message({
            showClose: true,
            message: "最多添加9个阶梯"
          });
        } else {
          this.editableTabs.push({
            title: "阶梯" + tabNum,
            name: "ladder" + tabNum,
            content: "New Tab content"
          });
          this.isAdding = true;
          this.editableTabsValue = "ladder" + tabNum;
          return "1";
        }
      } else {
        this.$message({
          message: "请先完成当前阶梯设置",
          type: "warning"
        });
      }
    },
    removeLadder(targetName) {
      this.$confirm("确认删除该阶梯?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let pos = targetName.slice(-1);
          let lotterData =
            this.$store.getters.getSecLotteryData ||
            this.$store.getters.getFirstLotteryData;
          let that = this;
          this.$fetch(DEL_LOTTERY, {
            id: this.lotterData[pos - 1].id
          })
            .then(res => {
              if (res.status == 1) {
                this.isRemove = true;
                this.getFirstLottery()/////////////////
                that.editableTabsValue = "ladder1";
                this.$message({
                  type: "success",
                  message: "删除成功!"
                });
              }
            })
            .catch(err => {
              console.log(err);
              this.$message({
                message: "删除失败",
                type: "warning"
              });
            });
        })
        .catch(() => {});
    }
  },
  beforeDestroy() {
    Bus.$off("refreshList");
    Bus.$off("refreshCoupon");
  }
};
</script>

<style>
.ladderBtns {
  position: fixed;
  bottom: 0.15rem;
  left: 40%;
}

.ladderBtns .btn {
  width: 0.8rem;
  height: 0.2rem;
  background: #3395ff;
  border-radius: 8px;
  color: #fff;
  margin-left: 0.2rem;
  top: 0;
}

/* .ladderBtns .next {
		background: #A9D0FF;
	} */
.ladderBox {
  display: flex;
  position: relative;
}
.addLadderBtn {
  width: 0.7rem;
  height: 0.23rem;
  line-height: 0.23rem;
  text-align: center;
  font-size: 0.1rem;
  cursor: pointer;
  border-bottom: 1px solid #f0f1f2;
  position: absolute;
  /* top: -.6%; */
  z-index: 4;
}
.addIcon {
  color: #3395ff;
  font-size: 0.15rem;
}
.ladderBox .el-tabs__nav-scroll {
  border-bottom: 1px solid #f0f1f2;
}

.ladderBox
  .el-tabs--card
  > .el-tabs__header
  .el-tabs__item.is-active.is-closable {
  background-color: #fff;
  border-top: none;
  border-bottom: 3px solid #3395ff;
}

.ladderBox .el-tabs--card > .el-tabs__header .el-tabs__item,
.ladderBox .el-tabs--card > .el-tabs__header .el-tabs__item:first-child {
  border: none;
}
.ladderBox .el-tabs--card > .el-tabs__header .el-tabs__item {
  background: none;
  width: 0.8rem;
  text-align: center;
  font-size: 0.1rem;
}
.ladderBox .el-tabs__nav div:first-child span {
  display: none;
}
.ladderBox .el-tabs--card > .el-tabs__header .el-tabs__item.is-active {
  border-bottom: 3px solid #3395ff !important;
}
</style>